package com.wtwd.campus.controller;

import com.alibaba.fastjson.JSONObject;
import com.github.xiaoymin.knife4j.annotations.DynamicParameter;
import com.github.xiaoymin.knife4j.annotations.DynamicParameters;
import com.wtwd.campus.common.Constants;
import com.wtwd.campus.common.RespCode;
import com.wtwd.campus.common.RespEntity;
import com.wtwd.campus.entity.*;
import com.wtwd.campus.service.*;
import com.wtwd.campus.utils.IpUtils;
import com.wtwd.campus.utils.Tools;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * @author mjy
 * @date 2021/06/07
 * @description
 */
@Api("用户管理")
@RestController
@RequestMapping("/user")
public class UserController {

    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
    @Autowired
    private UserService userService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private RolePermissionService rolePermissionService;
    @Autowired
    private LoginLogService loginLogService;
    @Autowired
    private SysOrgService sysOrgService;
    @Autowired
    private SchoolService schoolService;
    @Value("${logo.url}")
    private String realPath;
    @Value("${file.path}")
    private String filePath;
    @Value("${file.http}")
    private String fileHttp;

    /**
     * web用户登录
     *
     * @param jsonObject
     * @return
     */
    @ApiOperation("登录")
    @DynamicParameters(name = "json", properties = {
            @DynamicParameter(name = "username", value = "账号", dataTypeClass = Integer.class, required = true, example = "zdl")
            , @DynamicParameter(name = "password", value = "密码", dataTypeClass = String.class, required = true, example = "123")
    })
    @PostMapping("/login")
    public RespEntity login(@RequestBody JSONObject jsonObject, HttpServletRequest request, HttpServletResponse response) {
        logger.info("userLogin : param " + jsonObject, request);
        String account = jsonObject.getString("username");
        String password = jsonObject.getString("password");
        Object checkResult = userService.checkUser(account, password);
        if (checkResult instanceof RespEntity) {
            return (RespEntity) checkResult;
        }
        SysUser sysUser = (SysUser) checkResult;
        //获取当前用户
        String orgCode = sysUser.getOrgCode();
        SysOrg sysOrg = sysOrgService.getSysOrgByOrgCode(orgCode);
        if(sysOrg.getExpiresTime() != null && sysOrg.getExpiresTime() < System.currentTimeMillis()){
            return new RespEntity(RespCode.USER_ACCOUNT_OVERDUE);
        }
        //更新用户最近登录时间
        userService.updateUserLastLoginTimeByUserId(sysUser.getUserId(), System.currentTimeMillis());
        //记录的登录日志
        LoginLog loginLog = new LoginLog();
        String address = "";
        String ip = null;
        try {
            ip = IpUtils.getIpAddress(request);
        } catch (IOException e) {
            ip="获取ip地址失败";
        }
//        String ip = Integer.toString(request.getRemotePort());
        //通过ip获取到地址
        try {
            address = IpUtils.getAddressByIp(ip);
        } catch (Exception e) {// io异常,本机ip导致空指针问题，统一处理
            address = "获取位置信息失败";
        }
        loginLog.setIp(ip);
        loginLog.setLocation(address);
        loginLog.setLoginTime(System.currentTimeMillis());
        loginLog.setUserId(sysUser.getUserId());
        loginLog.setOrgCode(sysUser.getOrgCode());
        //记录登录日志
        loginLogService.addLoginLog(loginLog);
        //构建token数据(存入用户id,角色id)
        String token = Tools.getRamdomStr();
        redisService.createToken(sysUser, token);
        // 获取用户权限列表(获取所有权限列表,返回时注明是否有权)
        List<Map<String, Object>> userPermissionList = rolePermissionService.getRolePermissionList(sysUser.getRoleId());
        // 构建返回结果
        Map<String, Object> result = new HashMap<>();
        result.put("user_type", sysUser.getUserType());
        result.put("token", token);
        result.put("org_code",orgCode);
        result.put("permission_list", userPermissionList);
        result.put("user_name", sysUser.getAccount());
        result.put("ifAdmin","A01".equals(orgCode)?1:0);
        //鉴别是否是喜马拉雅的用户
        result.put("ifXmlyUser",orgCode.contains("A01A03A05")?1:0);
        //图片链接
        String path = "";
        String platformName = "";
//      根据用户id,获取系统名称
        PersonalSetting personalSetting = userService.getPersonalSetting(sysUser.getUserId());
        if (personalSetting != null) {
            if (!StringUtils.isBlank(personalSetting.getLogo_url())) {
                path = fileHttp.concat(realPath).concat(personalSetting.getLogo_url());
            }
            if (!StringUtils.isBlank(personalSetting.getPlatform_name())) {
                platformName = personalSetting.getPlatform_name();
            }
        }
        result.put("path", path);
        result.put("platformName", platformName);
        //平台名称
        return new RespEntity(RespCode.SUCCESS, result);
    }

    /**
     * logo图片上传
     *
     * @param file
     * @return
     */
    @PostMapping("/uploadLogoImg")
    public RespEntity uploadLogoImg(@RequestPart("file") MultipartFile file) {
        logger.info("uploadLogoImg");
        //校验文件的大小是否符合
        Double sizeDou = ((double) file.getSize()) / 1024;
        BigDecimal bd = new BigDecimal(sizeDou);
        double f1 = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        if (f1 > 1024) {
            return new RespEntity(RespCode.FILE_TOO_BIG);
        }
        //存储文件
        String fileName = UUID.randomUUID().toString().concat(file.getOriginalFilename());
        String saveUrl = filePath.concat(realPath).concat(fileName);
        File dest = new File(saveUrl);
        try {
            file.transferTo(dest);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new RespEntity(RespCode.SUCCESS, fileName);
    }

    /**
     * 修改或添加用户的个性设置
     *
     * @param data
     * @param request
     * @return
     */
    @PutMapping("/modifyPersonalSetting")
    public RespEntity modifyPersonalSetting(@RequestBody PersonalSetting data,
                                            HttpServletRequest request) {
        logger.info("modifyPersonalSetting : data= {}", data.toString());
        Integer userId = getUserOrgCode(request);
        Integer i = userService.addOrModifyPersonalSetting(userId, data.getPlatform_name(), data.getLogo_url());
        return new RespEntity(i > 0 ? RespCode.SUCCESS : RespCode.FAILED);
    }

    /**
     * 获取用户的个性化设置
     *
     * @param request
     * @return
     */
    @GetMapping("/getPersonalSetting")
    public RespEntity getPersonalSetting(HttpServletRequest request) {
        logger.info("getPersonalSetting ");
        Integer userId = getUserOrgCode(request);
        PersonalSetting personalSetting = userService.getPersonalSetting(userId);
        if (personalSetting != null) {
            return new RespEntity(RespCode.SUCCESS, personalSetting);
        } else {
            return new RespEntity(RespCode.NO_PERSONAL_SETTING);
        }

    }

    /**
     * 获取用户Id
     *
     * @param request
     * @return
     */
    public Integer getUserOrgCode(HttpServletRequest request) {
        //获取用户的组织编号
        String token = request.getHeader(Constants.HEADER_TOKEN_KEY);
        Map<String, Object> msg = redisService.getUserInfoByToken(token);
        String userMsg = (String) msg.get("user");
        JSONObject jsonObject = JSONObject.parseObject(userMsg);
        Integer userOrgCode = (Integer) jsonObject.get("userId");
        return userOrgCode;
    }

}
